/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package APP2.bookshop.controller;

import APP2.bookshop.book.Book;
import APP2.bookshop.author.Author;
import APP2.bookshop.main.BookShop;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author finalfire
 */
public class AuthorController {

    private BookShop bookshop;

    public AuthorController(BookShop bookshop) {
        this.bookshop = bookshop;
    }

    public boolean addAuthor(String name) {
        if (name != null) {
            this.bookshop.getAuthors().add(new Author(name));
            return true;
        }

        return false;
    }

    public Author getAuthorByName(String name) {
        Author corr = null;
        for (Author a : this.bookshop.getAuthors())
            if (a.getName().equals(name))
                corr = a;
        return corr;
    }

    public boolean deleteAuthor(Author a) {
        // delete from the books
        for (Book b : this.bookshop.getBooks())
            if (b.getAuthor().remove(a))
                System.out.println(a.getName() + " removed from " + b.getTitle());

        // delete from authors
        if (this.bookshop.getAuthors().remove(a))
            return true;

        return false;
    }

    // Return an AbstractListModel for JList component
    public javax.swing.AbstractListModel getAuthorsModel() {
        // create a new array to save authors' name
        final String[] elements = new String[this.bookshop.getAuthors().size()];
        for (int i = 0; i < elements.length; i++)
            elements[i] = this.bookshop.getAuthors().get(i).getName();

        // return a new AbstractListModel
        return UtilController.getListModelFromArray(elements);
    }

    public javax.swing.AbstractListModel getAllBooksByAuthor(String name) {
        return this.getAllBooksByAuthor(this.getAuthorByName(name));
    }
    public javax.swing.AbstractListModel getAllBooksByAuthor(Author a) {
        String[] books = new String[a.getBooks().size()];
        int i = 0;
        for (Book b : a.getBooks()) {
            books[i] = b.getTitle();
            i++;
        }
        return UtilController.getListModelFromArray(books);
    }
}
